/*
 * @Description: 点赞按钮
 * @Author: yangrongxin
 * @Date: 2021-05-12 10:24:43
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:25:13
 */
import React, { useState, useEffect } from 'react';
import { View, Canvas } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { AtIcon } from 'taro-ui';
import { debounce } from 'lodash';
import lottie from 'lottie-miniprogram';
import likeJson from '@/const/like';
import { likeArticle } from '@/pages/PatientEducation/service';
import styles from './index.module.less';

interface ILikeComponentProps {
  articleId: string; // 需要进行点赞的文章id
  like: boolean; // 当前是否是点赞的状态
  callback?: any; // 当前进行点赞的回调
}

const LikeComponent: React.FC<ILikeComponentProps> = (props) => {
  const { articleId, like = false, callback } = props;

  const [curLike, setCurLike] = useState(like);

  const [renderLottie, setRenderLottie] = useState(false);

  useEffect(() => {
    setCurLike(like);
  }, [like]);

  let likeBtn: any;

  const initLike = () => {
    if (likeBtn) return;
    Taro.createSelectorQuery()
      .select(`#canvas${articleId}`)
      .node((res: any) => {
        const canvas = res.node;
        const context = canvas.getContext('2d');
        lottie.setup(canvas);
        likeBtn = lottie.loadAnimation({
          rendererSettings: {
            context,
          },
          loop: false,
          autoplay: false,
          animationData: likeJson,
        });
        setRenderLottie(true);
      })
      .exec();
    // 根据当前传入的状态 初始化一个状态
  };

  return (
    <View
      catchMove
      className={styles.wapperContainer}
      onClick={debounce((event: any) => {
        event?.preventDefault && event?.preventDefault();
        event?.stopPropagation && event?.stopPropagation();
        initLike();
        likeArticle({
          articleId,
          like: !curLike,
        }).then((res: any) => {
          if (res?.errCode === '0') {
            !curLike ? likeBtn.play() : likeBtn.stop();
            setCurLike(!curLike);
            callback(!curLike);
          }
        });
      }, 500)}
    >
      {!renderLottie && <AtIcon value="heart-2" size="20" color={!curLike ? '#ccc' : '#EF3D20'} />}
      <Canvas id={`canvas${articleId}`} type="2d" />
    </View>
  );
};

export default LikeComponent;
